package com.ahj.location;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.qingning.qn.R;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;
import utils.ToastUtils;


public class LocationActivity extends FlutterActivity implements View.OnClickListener, AMapLocationListener,
        PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener {
    private ImageView imgBack;
    private TextView tvOk, tvCancle;
    private EditText etSearch;
    private ImageView imgClose;
    private View view;
    private MapView map;
    private ListView lv;
    private ArrayList<PoiItem> list = new ArrayList<>();
    private AdapterSearch adapter;

    private LinearLayout llResult;
    private ListView lvAuto;
    private ArrayList<Tip> listAuto = new ArrayList<>();
    private AdapterSearch adapterAuto;

    private String companyAddress;

    private AMap aMap;
    private PoiSearch poiSearch;
    private Marker marker;//当前添加的marker
    //获取当前位置定位对象
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption = null;
    private boolean inputSearch = false;
    private float zoom = 15;
    private String ChannelTag = "com.qingning.qn/ChoiceLocationUtils";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_location);

        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);

        initView();
        addListener();

        initMap(savedInstanceState);
    }

    // 当前输入的时间
    private long curTime = 0;
    private Timer timer;
    private TimerTask task;
    // 是否自动提示
    private boolean isAuto = true;

    private void startTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }

        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                curTime = 0;
                autoWord(etSearch.getText().toString().trim());
            }
        };
        timer.schedule(task, 500);
    }

    private void stopTimer() {
        curTime = 0;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    private void initView() {
        imgBack = findViewById(R.id.imgBack);
        tvOk = findViewById(R.id.tvOk);
        etSearch = findViewById(R.id.etSearch);
        imgClose = findViewById(R.id.imgClose);
        tvCancle = findViewById(R.id.tvCancle);
        view = findViewById(R.id.view);
        tvCancle = findViewById(R.id.tvCancle);
        map = findViewById(R.id.map);
        lv = findViewById(R.id.lv);
        lvAuto = findViewById(R.id.lvAuto);
        llResult = findViewById(R.id.llResult);

        companyAddress = getIntent().getStringExtra("address");

        adapter = new AdapterSearch(this, list, false);
        lv.setAdapter(adapter);

        adapterAuto = new AdapterSearch(this, listAuto, true);
        lvAuto.setAdapter(adapterAuto);
    }

    private void addListener() {
        imgBack.setOnClickListener(this);
        tvOk.setOnClickListener(this);
        imgClose.setOnClickListener(this);
        tvCancle.setOnClickListener(this);
        lv.setOnItemClickListener((parent, view, position, id) -> {
            adapter.setSelectIndex(position);
            LatLng point = new LatLng(list.get(position).getLatLonPoint().getLatitude(), list.get(position).getLatLonPoint().getLongitude());
            changeLocation(point);
        });

        lvAuto.setOnItemClickListener((parent, view, position, id) -> {
            // 更改地图中心点
            LatLng latLng = new LatLng(
                    listAuto.get(position).getPoint().getLatitude(),
                    listAuto.get(position).getPoint().getLongitude());
            changeLocation(latLng);
            // 检索周边
            poiSearch("", "",
                    new LatLonPoint(latLng.latitude, latLng.longitude));


            tvCancle.setVisibility(View.GONE);
            this.view.setVisibility(View.VISIBLE);
            lvAuto.setVisibility(View.GONE);
            llResult.setVisibility(View.VISIBLE);
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0 || TextUtils.isEmpty(s)) {
                    //输入框内容为空  停止计时、隐藏清空按钮

                    stopTimer();
                    imgClose.setVisibility(View.GONE);
                    return;
                } else {
                    imgClose.setVisibility(View.VISIBLE);
                }
                if (!isAuto) {
                    isAuto = true;
                    stopTimer();
                    return;
                }
                if (curTime == 0 || System.currentTimeMillis() - curTime < 500) {
                    curTime = System.currentTimeMillis();
                    startTimer();
                } else {
                    stopTimer();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == imgBack.getId()) {
            back();
        }
        if (v.getId() == tvOk.getId()) {
            PoiItem item = adapter.getSelectItem();
            Map<String, Object> joData = new HashMap<>();
            joData.put("province", item.getProvinceName()); //省name        getProvinceName()
            joData.put("city", item.getCityName());     //市name        getCityName()
            joData.put("ad", item.getAdName());       //行政区name     getAdName()
            joData.put("snippet", item.getSnippet());  //地址信息       getSnippet()
            joData.put("title", item.getTitle());    //名称           getTitle()
            joData.put("lng", item.getLatLonPoint().getLongitude());//经度 getLatLonPoint().getLongitude()
            joData.put("lat", item.getLatLonPoint().getLatitude());//纬度  getLatLonPoint().getLatitude()
            ChoiceLocationPlugin.mResult.success(joData);
//            MethodChannel methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor()
//                    .getBinaryMessenger(), ChannelTag);
//            methodChannel.invokeMethod("location", joData);
            finish();
        }
        if (v.getId() == imgClose.getId()) {
            etSearch.setText("");
        }
        if (v.getId() == tvCancle.getId()) {
            etSearch.setText("");
            tvCancle.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);
            lvAuto.setVisibility(View.GONE);
            llResult.setVisibility(View.VISIBLE);
        }
    }

    // 获取搜索自动提示
    private void autoWord(String word) {
        InputtipsQuery inputquery = new InputtipsQuery(word, null);
        Inputtips inputTips = new Inputtips(this, inputquery);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
    }

    // 自动提示返回内容
    @Override
    public void onGetInputtips(List<Tip> list, int i) {
        listAuto.clear();
        if (list != null) {
            listAuto.addAll(list);
        }
        adapterAuto.notifyDataSetChanged();

        tvCancle.setVisibility(View.VISIBLE);
        view.setVisibility(View.GONE);
        lvAuto.setVisibility(View.VISIBLE);
        llResult.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private void back() {
        finish();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (poiResult.getPois() != null) {
            list.clear();
            list.addAll(poiResult.getPois());
            adapter.reset();
            if (list.size() > 0) {
                lv.setSelection(0);
                if (inputSearch) {
                    // 更改地图中心点
                    LatLonPoint point = list.get(0).getLatLonPoint();
                    changeLocation(new LatLng(point.getLatitude(), point.getLongitude()));
                    inputSearch = false;
                }
            }
        }
    }

    private void initMap(Bundle savedInstanceState) {
        //在activity执行onCreate时执行map.onCreate(savedInstanceState)，创建地图
        map.onCreate(savedInstanceState);
        aMap = map.getMap();
        // 改变地图缩放级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));

        //地图添加点击事件
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                zoom = aMap.getCameraPosition().zoom;
                // 更改地图中心点
                changeLocation(latLng);
                // 检索周边
                poiSearch("", "",
                        new LatLonPoint(latLng.latitude, latLng.longitude));
            }
        });

        //判断如果传过来有默认的公司位置信息，就定位到公司位置信息，没有的话获取当前定位
        if (TextUtils.isEmpty(companyAddress)) {
            //获取当前定位
            try {
                mlocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setOnceLocation(true);
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //启动定位
            mlocationClient.startLocation();
        } else {
            //检索公司位置
            inputSearch = true;
            poiSearch(companyAddress, "", null);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                amapLocation.getCountry();//国家信息
                amapLocation.getProvince();//省信息
                amapLocation.getCity();//城市信息
                amapLocation.getDistrict();//城区信息
                amapLocation.getStreet();//街道信息
                amapLocation.getStreetNum();//街道门牌号信息
                amapLocation.getCityCode();//城市编码
                amapLocation.getAdCode();//地区编码
                amapLocation.getAoiName();//获取当前定位点的AOI信息

                Log.e("location",
                        "纬度 Latitude = " + amapLocation.getLatitude() + "\n" +
                                "经度 Longitude = " + amapLocation.getLongitude() + "\n" +
                                "获取精度信息 Accuracy = " + amapLocation.getAccuracy() + "\n" +
                                "地址 Address = " + amapLocation.getAddress() + "\n" +
                                "省 Province = " + amapLocation.getProvince() + "\n" +
                                "城市 City = " + amapLocation.getCity() + "\n" +
                                "城区 District = " + amapLocation.getDistrict() + "\n" +
                                "街道 Street = " + amapLocation.getStreet() + "\n" +
                                "街道门牌号 StreetNum = " + amapLocation.getStreetNum() + "\n" +
                                "城市编码 CityCode = " + amapLocation.getCityCode() + "\n" +
                                "地区编码 getAdCode = " + amapLocation.getAdCode() + "\n" +
                                "获取当前定位点的AOI getAoiName = " + amapLocation.getAoiName()
                );
                mlocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                // 更改地图中心点
                changeLocation(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
                // 检索周边
                poiSearch("", amapLocation.getCityCode(),
                        new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude()));
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                ToastUtils.showToast(this, "获取位置信息失败");
//                Log.e("AmapError", "location Error, ErrCode:"
//                        + amapLocation.getErrorCode() + ", errInfo:"
//                        + amapLocation.getErrorInfo());
            }
        }
    }

    //更改地图中心点
    private void changeLocation(LatLng point) {
        // 参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition
                (new CameraPosition(point, zoom, 0, 0));

        //aMap.animateCamera  带移动动画
        //aMap.moveCamera     不带移动动画
        aMap.animateCamera(mCameraUpdate);

        if (marker != null) {
            marker.destroy();
            marker = null;
        }
        // 添加marker
        marker = aMap.addMarker(new MarkerOptions().position(point).title("").snippet(""));
    }

    //poi检索
    private void poiSearch(String keyWord, String cityCode, LatLonPoint point) {
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "", cityCode);
        query.setPageSize(50);
        try {
            poiSearch = new PoiSearch(this, query);
        } catch (AMapException e) {
            e.printStackTrace();
            ToastUtils.showToast(this, "检索位置信息失败");
            return;
        }
        poiSearch.setOnPoiSearchListener(this);

        if (point != null) {
            //设置周边搜索参数
            poiSearch.setBound(new PoiSearch.SearchBound(point, 1000));//设置周边搜索的中心点以及半径
        }
        // 执行检索
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
        list.clear();
        list.add(poiItem);
        adapter.reset();
        if (list.size() > 0) {
            lv.setSelection(0);
            if (inputSearch) {
                // 更改地图中心点
                LatLonPoint point = list.get(0).getLatLonPoint();
                changeLocation(new LatLng(point.getLatitude(), point.getLongitude()));
                inputSearch = false;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行map.onDestroy()，销毁地图
        if (map != null)
            map.onDestroy();

        //销毁定位客户端，同时销毁本地定位服务。
        if (mlocationClient != null)
            mlocationClient.onDestroy();

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }

        if (mlocationClient != null) {
            /*
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            try {
                mlocationClient.onDestroy();
                mlocationClient = null;
                mLocationOption = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行map.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行map.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行map.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }


}
